package com.patrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.patrol.dao.UserDao;
import com.patrol.pojo.User;
import com.patrol.service.EmailCodeService;
import com.patrol.utils.VerCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 房梦豪
 * @version 1.0
 * @description: TODO
 * @date 2021/9/5 9:49
 */
@Service
public class EmailCodeServiceImpl implements EmailCodeService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Resource
    private UserDao userDao;

    @Value("${spring.mail.username}")
    private String sender;

    @Autowired
    private RedisTemplate redisTemplate;

    @Async
    @Override
    public boolean sendEmailCode(String receiver, String username) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", username);
        qw.eq("email", receiver);
        User adminUser = userDao.selectOne(qw);
        if (null != adminUser) {
            String code = VerCodeUtil.generateVerCode();
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("验证码");
            message.setText("尊敬的用户,您好:\n"
                    + "\n本次请求的邮件验证码为:" + code + ",本验证码2分钟内有效，请及时输入。（请勿泄露此验证码）\n"
                    + "\n如非本人操作，请忽略该邮件。\n(这是一封自动发送的邮件，请不要直接回复）");	//设置邮件正文
            message.setTo(receiver);	//设置收件人
            message.setFrom(sender);	//设置发件人
            mailSender.send(message);	//发送邮件
            redisTemplate.opsForValue().set(receiver, code);  //key:receiver  value:code
            redisTemplate.expire(receiver,120, TimeUnit.SECONDS);   //有效时间两分钟
            return true;
        }
        return false;
    }
}
